//
//  HDLoginViewController.swift
//  HuaDaoPeifu
//
//  Created by Erickson on 16/4/7.
//  Copyright © 2016年 paiyipai. All rights reserved.
//

import UIKit
import SVProgressHUD
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}

// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l > r
  default:
    return rhs < lhs
  }
}

class HDLoginViewController: UIViewController ,UITextFieldDelegate{
    
    let phoneView = HDIconTextFieldView()
    let passWDView = HDIconTextFieldView()
    
    var progressAlert = HDProgressAlert()
    //在登录页点击注册跳到哪里：0表示pop到上一页(个人中心需求)，1表示push到注册页(首页登录需求)
    var registerBtnBackToWhere: Int?
    var passTiaoZhuan: Int?
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor(hex: 0xf8f8f8)
        title = "登录"
        setupView()
        let nextBtn = HDNextStepButton(title:"登录")
        view.addSubview(nextBtn)
        nextBtn.snp.makeConstraints { (make) in
            make.top.equalTo(passWDView.snp.bottom).offset(50)
            make.left.equalTo(view).offset(37)
            make.right.equalTo(view).offset(-37)
            make.height.equalTo(40)
        }
        nextBtn.addTarget(self, action: #selector(HDLoginViewController.nextStep), for: .touchUpInside)
        
        let registerButton = UIButton(type: .custom)
        registerButton.setTitle("注册账号", for: UIControlState())
        registerButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        registerButton.setTitleColor(ConstantColor.appThemeColor, for: UIControlState())
        registerButton.isHidden = false
        registerButton.addTarget(self, action: #selector(registerButtonAction), for: .touchUpInside)
        view.addSubview(registerButton)
        registerButton.snp.makeConstraints { (make) in
            make.left.equalTo(37)
            make.top.equalTo(nextBtn.snp.bottom).offset(10)
            make.width.equalTo(66)
            make.height.equalTo(15)
        }
        
        let forgetButton = UIButton(type: .custom)
        forgetButton.setTitle("忘记密码?", for: UIControlState())
        forgetButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        forgetButton.setTitleColor(ConstantColor.appThemeColor, for: UIControlState())
        forgetButton.addTarget(self, action: #selector(forgetButtonAction), for: .touchUpInside)
        view.addSubview(forgetButton)
        forgetButton.snp.makeConstraints { (make) in
            make.right.equalTo(-37)
            make.top.equalTo(nextBtn.snp.bottom).offset(10)
            make.width.equalTo(66)
            make.height.equalTo(15)
        }
        setBarButton()
    }
    
    func setBarButton() {
        let guideLogin = UserDefaults.standard.bool(forKey: "Guide")
        if guideLogin {
            navigationItem.rightBarButtonItem = nil
            navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "back"), style: .plain, target: self, action: #selector(backToGuide))
        }
    }
    func backToGuide() {
        phoneView.textField.resignFirstResponder()
        passWDView.textField.resignFirstResponder()
        let backGuide = GuideViewController()
        UIApplication.shared.keyWindow?.rootViewController = backGuide;
        backGuide.scrollView.contentOffset.x = AppConstant.screenWidth*4
        backGuide.scrollView.isScrollEnabled = false
        UserDefaults.standard.set(false, forKey: "Guide")
        self.dismiss(animated: true, completion: nil)
        
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        phoneView.textField.resignFirstResponder()
        passWDView.textField.resignFirstResponder()
    }
    
    /**
     *注册账号
     */
    func registerButtonAction() {
        let register = HDRegisterViewController(regType: .register)
        register.logBtnBackToWhere = passTiaoZhuan
        register.passType = 1
        if registerBtnBackToWhere == 1 {
            navigationController?.popViewController(animated: true)
        }else {
            navigationController?.pushViewController(register, animated: true)
        }
        
    }
    
    /**
     *忘记密码
     */
    func forgetButtonAction() {
        navigationController?.pushViewController(HDForgetPWViewController(), animated: true)
    }
    
    /**
     登录
     */
    func nextStep() {
//        phoneView.textField.resignFirstResponder()
//        passWDView.textField.resignFirstResponder()
//        
//        if phoneView.textField.text == nil || phoneView.textField.text == "" {
//            SVProgressHUD.showError("手机号不能为空")
//            return
//        }
//        if phoneView.textField.text?.characters.count != 11 {
//            SVProgressHUD.showError("手机号错误")
//            return
//        }
//        if passWDView.textField.text == nil || passWDView.textField.text == "" {
//            SVProgressHUD.showError("密码不能为空")
//            return
//        }
//        if passWDView.textField.text?.characters.count < 6 || passWDView.textField.text?.characters.count > 16 {
//            SVProgressHUD.showError("密码错误")
//            return
//        }
//        let passWordStr = passWDView.textField.text
//        let ptxtStr = passWordStr?.md5()
//        let udid = UIDevice.current.identifierForVendor?.uuidString
//        let ckAuthCode = PYPLogin(phone: phoneView.textField.text,ptxt: ptxtStr, did:udid)
//        
//        // 登录
//        HDApiManagerHandler.requestLogin(ckAuthCode, success: { [unowned self](dict) in
//            print(dict)
//            
//            if dict["status"]?.int32Value == 1 {
//                let regRespon = dict["data"] as! [String:AnyObject]
//                
//                let regR = PYPRegRespond.parse(regRespon as NSDictionary)
//                HDAccountHandler.token = regR.token!
//                HDAccountHandler.saveUserToken(regR.token!)
//                HDAccountHandler.saveUserIntType((regR.user_type?.intValue)!)
//                HDAccountHandler.saveUserPhone(self.phoneView.textField.text!)
//                
//                NotificationCenter.default.post(name: Notification.Name(rawValue: HDUserNotification.userlogin), object: nil)
//                let a = UserDefaults.standard.bool(forKey: "Guide")
//                if a {
//                    let vc = ViewController();
//                    UIApplication.shared.keyWindow?.rootViewController = vc;
//                    self.dismiss(animated: true, completion: nil)
//                    
//                    UserDefaults.standard.set(false, forKey: "Guide")
//                }else{
//                    self.navigationController?.popToRootViewController(animated: true)
//                }
//                
//            }else {
//                let msg = dict["msg"] as! String
//                SVProgressHUD.showError(msg)
//            }
//        }) { (error) in
//            
//        }
    }
    
    func setupView() {
        phoneView.icon.image = UIImage(named: "phone")
        phoneView.textField.clearButtonMode = .whileEditing
        phoneView.textField.placeholder = "请输入手机号码"
        phoneView.textField.keyboardType = .numberPad
        self.view.addSubview(phoneView)
        phoneView.snp.makeConstraints { (make) in
            make.top.equalTo(45)
            make.left.equalTo(self.view).offset(-1)
            make.right.equalTo(self.view).offset(1)
            make.height.equalTo(49)
        }
        
        passWDView.icon.image = UIImage(named: "lock")
        passWDView.textField.placeholder = "请输入密码"
        passWDView.textField.clearButtonMode = .whileEditing
        passWDView.textField.isSecureTextEntry = true
        passWDView.getCodeButton.addTarget(self, action: #selector(HDRegisterViewController.getCode), for: .touchUpInside)
        self.view.addSubview(passWDView)
        passWDView.snp.makeConstraints { (make) in
            make.top.equalTo(phoneView.snp.bottom).offset(10)
            make.left.equalTo(self.view).offset(-1)
            make.right.equalTo(self.view).offset(1)
            make.height.equalTo(49)
        }
    }
}


